﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Mimoza.UpdatePlugin
{
    public class ExecutePlugin : Mimoza.PluginLayer.IExecutePlugin, IDisposable
    {
        public ExecutePlugin()
        {
            CheckStartDownload();
        }

        #region IDisposable Members

        public void Dispose()
        {
            StopDownload();
        }

        #endregion


        #region IExecutePlugin Members

        public string PluginId
        {
            get { return this.ToString(); }
        }

        public void Add(Mimoza.ObjectLayer.Policy policy)
        {
            Add(policy, GetData(policy.Data));
        }

        public void Remove(Mimoza.ObjectLayer.Policy policy)
        {
            Remove(policy, GetData(policy.Data));
        }

        public void Update(Mimoza.ObjectLayer.Policy policy)
        {
            Update(policy, GetData(policy.Data));
        }

        #endregion

        public void SetServiceConnection(Transport.Connection connection)
        {
            m_serviceConnection = connection;
        }

        void Add(Mimoza.ObjectLayer.Policy policy, UpdatePluginData data)
        {
            Trace("Add", policy, data);

            if (!IsUpdatesFileSuitable(data)) return;

            CreateUpdatesFile(data.UpdateId.ToString(), policy.ID.ToString());

            CheckStartDownload();
        }

        void Update(Mimoza.ObjectLayer.Policy policy, UpdatePluginData data)
        {
            Trace("Update", policy, data);

            Add(policy, data);
        }

        void Remove(Mimoza.ObjectLayer.Policy policy, UpdatePluginData data)
        {
            Trace("Remove", policy, data);

            StopDownload();
            EraseUpdatesFile(data.UpdateId.ToString(), policy.ID.ToString());

            CheckStartDownload();
        }


        void Trace(string operationName, Mimoza.ObjectLayer.Policy policy, UpdatePluginData data)
        {
            Common.Logger.Log.Info("Mimoza.UpdatePlugin.ExecutePlugin." + operationName + 
                " Name - '" + policy.Name +
                "' UpdateId - '" + data.UpdateId.ToString() + "'.");
        }

        UpdatePluginData GetData(string data)
        {
            return UpdatePluginData.Deserialize(data);
        }

        void CheckStartDownload()
        {
            string workingFileName = GetUpdatesFirstFileName();
            bool bUpdateFileExists = (workingFileName!=null);

            Common.Logger.Log.Info("Mimoza.UpdatePlugin.ExecutePlugin.CheckStartDownload bUpdateFileExists - " +
                bUpdateFileExists.ToString() + "...");

            if (!bUpdateFileExists || m_fileDownloader!=null) return;

            m_fileDownloader = new UpdateFileDownloader();
            m_fileDownloader.SetServiceConnection(m_serviceConnection); 
            m_fileDownloader.Start(workingFileName);
        }

        void StopDownload()
        {
            if (m_fileDownloader != null)
            {
                m_fileDownloader.Stop();
                m_fileDownloader = null;
            }
        }

        private static string GetUpdatesFirstFileName()
        {
            Directory.CreateDirectory(UpdatesFilesFolder);

            foreach (string fileName in Directory.GetFiles(UpdatesFilesFolder, "*.*"))
            {
                return fileName;
            }

            return null;
        }

        private static void CreateUpdatesFile(string updateId, string policyID)
        {
            Directory.CreateDirectory(UpdatesFilesFolder);

            string fileName = Path.Combine(UpdatesFilesFolder, updateId + "." + policyID);

            if (!File.Exists(fileName))
            {
                using (FileStream stream = File.Create(fileName))
                {
                }
            }
        }

        private static void EraseUpdatesFile(string updateId, string policyID)
        {
            string fileName = UpdatesFilesFolder + updateId + "." + policyID;

            Common.Logger.Log.Info("Mimoza.UpdatePlugin.EraseUpdatesFile fileName - '" + fileName +
                "'." );

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
        }

        private static bool IsUpdatesFileSuitable(UpdatePluginData data)
        {
            bool bres = false;
            //if (Mimoza.Common.GlobalSettings.Licence.ModelName == data.ModelName &&
              //  Mimoza.Common.GlobalSettings.Licence.OSName == data.OSName) bres = true;
bres = true;

            Common.Logger.Log.Info("Mimoza.UpdatePlugin.IsUpdatesFileSuitable res - {0} data.ModelName - '{1}' data.OSName - '{2}'.", 
                bres.ToString(), data.ModelName, data.OSName );

            return bres;
        }

        public static string UpdatesFilesFolder
        {
            get
            {
                return Path.Combine(Common.GlobalSettings.DataPath, "updates");
            }
        }

        UpdateFileDownloader m_fileDownloader = null;
        Transport.Connection m_serviceConnection;
    }
}
